import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store/index.js'

// 基础设置
const service = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  async (config) => {
    // IP地址
    const ip = localStorage.getItem('ip')
    if (ip) {
      config.headers.ip = ip
    } else {
      const res = await fetch('https://api.ipify.org?format=json').then(
        (response) => response.json()
      )
      res.ip && localStorage.setItem('ip', res.ip)
      config.headers.ip = res.ip
    }
    // 设置请求头 Token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = token
      return config
    }
    return config
  },
  (error) => {
    return Promise.reject(new Error(error))
  }
)

//响应拦截器
service.interceptors.response.use(
  (response) => {
    const { data } = response
    // status = 0 为成功
    if (data.status === 0 || data.status === 1) {
      return data
    } else if (data.status === 99) {
      // token已过期
      store.dispatch('app/logout')
      return Promise.reject(new Error('token 失效了'))
    } else {
      ElMessage.error(data.message)
      return Promise.reject(new Error(data.message))
    }
  },
  (error) => {
    // 服务没启动等
    store.dispatch('app/logout')
    error.response && ElMessage.error(error.response.data || '服务未启动等...')
    return Promise.reject(new Error(error.response.data))
  }
)

export default service
